import { SettingsService, ModalHelper } from '@delon/theme';
import {
  Component,
  OnDestroy,
  Inject,
  Optional,
  Injector,
} from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ReuseTabService } from '@delon/abc';

import { LoginService } from './login.service';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/component-base/app-component-base';

@Component({
  selector: 'hc-login',
  templateUrl: './hc-login.component.html',
  styleUrls: ['./hc-login.component.less'],
  animations: [appModuleAnimation()],
  providers: [LoginService],
})
export class HCLoginComponent extends AppComponentBase implements OnDestroy {
  form: FormGroup;
  error = '';
  type = 0;
  isHandover: boolean = false;
  loading = false;

  constructor(
    injector: Injector,
    fb: FormBuilder,
    modalSrv: NzModalService,
    public msg: NzMessageService,
    public loginService: LoginService,
  ) {
    super(injector);
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(1)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true],
    });
    modalSrv.closeAll();
  }

  get userName() {
    return this.form.controls.userName;
  }
  get password() {
    return this.form.controls.password;
  }

  count = 0;
  interval$: any;

  submit() {
    this.error = '';
    this.userName.markAsDirty();
    this.userName.updateValueAndValidity();
    this.password.markAsDirty();
    this.password.updateValueAndValidity();
    if (this.userName.invalid || this.password.invalid) return;

    this.loginService.authenticateModel.userNameOrEmailAddress = this.userName.value;
    this.loginService.authenticateModel.password = this.password.value;
    this.loginService.rememberMe = this.form.controls.remember.value;
    this.loading = true;
    this.loginService.authenticate(() => {
      this.loading = false;
    });
  }

  get multiTenancySideIsTeanant(): boolean {
    return this.appSession.tenantId > 0;
  }

  get isSelfRegistrationAllowed(): boolean {
    if (!this.appSession.tenantId) {
      return false;
    }
    return true;
  }

  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$);
  }
}
